var segment = []; // segment:'',provider:''
$(function() {
    $.get(
        "/m/provider/segment",
        {},
        function(res) {
            if(res.code === 0) {
                segment = res.list;
                console.log(segment);
            }
        }
    );
    $("#choose").on('mouseover', function() {
        layer.tips('仅支持导入 TXT / XLS / XLSX 格式的文件，每行一个号码', this, {
            tips: [3, '#3595CC'],
            time: 3000
        });
    })
});
layui.use(['form', 'upload'], function() {
    var form = layui.form, upload = layui.upload;
    form.on('submit(split)', function(data) {
        clear_split();
        var params = data.field;
        var arr = params['whole'].split("\n");
        arr = distinct_array(arr);
        if(arr.length === 0) {
            layer.msg("请先输入手机号码！");
            return;
        }
        var load_lay = layer.load(0);
        var mobile, segRex, provider;
        var regexp;
        var cmcc = [], cucc = [], ctcc = [], unknown = [];
        for(var i in arr) {
            mobile = arr[i];
            if(mobile === '') {
                continue;
            }
            for(var j in segment) {
                segRex = segment[j].segment;
                provider = segment[j].provider;
                //regexp = new RegExp(segRex);
                if(segRex.test(mobile)) {
                    if("CMCC" === provider) {
                        cmcc.push(mobile);
                    }
                    else if("CUCC" === provider) {
                        cucc.push(mobile);
                    }
                    else {
                        ctcc.push(mobile);
                    }
                    mobile = '';
                    break;
                }
            }
            if(mobile !== '') {
                unknown.push(mobile);
            }
        }
        $("#cmcc").val(cmcc.join('\n'));
        $("#cucc").val(cucc.join('\n'));
        $("#ctcc").val(ctcc.join('\n'));
        $("#unknown").val(unknown.join('\n'));
        layer.close(load_lay);
        layer.msg('分流已完成');
    });
    upload.render({
        elem: '#choose',
        url: '/m/number/reader',
        accept: 'file',
        exts: 'txt|xls|xlsx',
        auto: false,
        bindAction: '#imp',
        done: function(res) {
            if(res.code === 0) {
                var numbers = res.data.numbers;
                if(numbers.length > 0) {
                    $("#whole").val(numbers.join('\n'));
                }
                layer.msg('成功导入' + numbers.length + '个手机号码');
            }
            else {
                layer.msg('导入失败：' + res.message);
            }
        }
    });
});

function clear_split() {
    $("#cmcc").val('');
    $("#cucc").val('');
    $("#ctcc").val('');
    $("#unknown").val('');
}